package com.beijiteshop.shop.base

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.beijiteshop.libcommon.base.activity.BaseActivity
import com.beijiteshop.shop.R
import com.beijiteshop.shop.app.PageIndex
import com.beijiteshop.shop.databinding.ActivityFragmentContanierBinding
import com.beijiteshop.shop.model.api.response.AddressBean
import com.beijiteshop.shop.model.api.response.ProductBean
import com.beijiteshop.shop.ui.account.fragment.AccountFragment
import com.beijiteshop.shop.ui.account.fragment.BindPhoneFragment
import com.beijiteshop.shop.ui.address.fragment.AddAddressFragment
import com.beijiteshop.shop.ui.address.fragment.AddressFragment
import com.beijiteshop.shop.ui.category.fragment.CategoryFragment
import com.beijiteshop.shop.ui.coupon.fragment.CouponFragment
import com.beijiteshop.shop.ui.detail.ProductDetailFragment
import com.beijiteshop.shop.ui.notification.fragment.NotifyDetailFragment
import com.beijiteshop.shop.ui.order.fragment.*


/**
 * @Author LiaoZhongKai
 * @Date 2021/3/8 10:31
 * @Description 所有页面都用Fragment,该Activity承载多个Fragment，并进行Fragment之间的切换
 */
class FragmentContainerActivity : BaseActivity<ActivityFragmentContanierBinding>(),IFragmentContainerListener{

    companion object{

        private const val BUNDLE_FRAGMENT = "bundle_fragment"

        /**
         * 启动Activity
         * @param fragment 要启动Fragment的标记
         * @param bundle 传递给Fragment的参数
         */
        open fun start(context: Context,fragment: Int,bundle: Bundle? = null){
            val intent = Intent(context,
                FragmentContainerActivity::class.java).apply {
                var bundleExtra = bundle
                if (bundleExtra == null){
                    bundleExtra = Bundle()
                }
                bundleExtra.putInt(BUNDLE_FRAGMENT,fragment)
                putExtras(bundleExtra)
            }
            context.startActivity(intent)
        }

    }

    private var mFragmentIndex: Int = -1
    private var mBundle: Bundle? = null
    private val mFragmentList = mutableListOf<Fragment>()

    override fun getLayoutRes(): Int {
        return R.layout.activity_fragment_contanier
    }

    override fun initView(savedInstanceState: Bundle?) {

        mBundle = intent?.extras
        mBundle?.let {
            mFragmentIndex = it.getInt(BUNDLE_FRAGMENT)
            if ( mFragmentIndex >= 0){
                switchFragment(mFragmentIndex)
            }else{
                finish()
            }
        }
    }

    override fun initData() {

    }

    override fun initEvent() {

    }

    /**
     * 切换Fragment
     * @param bundle fragment之间切换时需要传递的参数
     * mBundle Activity传递到fragment的参数
     */
    override fun switchFragment(index: Int, bundle: Bundle?){
        val transaction = supportFragmentManager.beginTransaction()
        hideAllFragments(transaction)
        var fragment: Fragment? = null
        //========添加Fragment=========
        when(index){
            PageIndex.PRODUCT_DETAIL -> {
                val product = mBundle?.getParcelable<ProductBean>(ProductDetailFragment.BUNDLE_PRODUCT)
                product?.let {
                    fragment = ProductDetailFragment.newInstance(it)
                }
            }
            PageIndex.ORDER_CONFIRM -> {
                val product = mBundle?.getParcelable<ProductBean>(OrderConfirmFragment.BUNDLE_PRODUCT)
                if (product != null ){
                    fragment = OrderConfirmFragment.newInstance(product)
                }
            }
            PageIndex.ADDRESS -> {
                val isSelect = mBundle?.getBoolean(AddressFragment.BUNDLE_IS_SELECT)?:true
                fragment = AddressFragment.newInstance(isSelect)
            }
            PageIndex.ADD_ADDRESS -> {
                val type = mBundle?.getInt(AddAddressFragment.BUNDLE_TYPE)
                val address = mBundle?.getParcelable<AddressBean>(AddAddressFragment.BUNDLE_ADDRESS)
                fragment = AddAddressFragment.newInstance(type?:AddAddressFragment.TYPE_ADD,address)
            }
            PageIndex.CATEGORY -> {
                fragment = CategoryFragment.newInstance()
            }
            PageIndex.ORDER_TAB -> {
                val index = mBundle?.getInt(OrderTabFragment.BUNDLE_DEFAULT_INDEX,0)?:0
                fragment = OrderTabFragment.newInstance(index)
            }
            PageIndex.ORDER_DETAIL -> {
                val orderId = mBundle?.getString(OrderDetailFragment.BUNDLE_ORDER_ID)
                orderId?.let {
                    fragment = OrderDetailFragment.newInstance(it)
                }
            }
            PageIndex.ORDER_PAY -> {
                val orderNum = mBundle?.getString(OrderPayFragment.BUNDLE_ORDER_NUMBER)
                orderNum?.let {
                    fragment = OrderPayFragment.newInstance(orderNum)
                }
            }
            PageIndex.NOTIFICATION_DETAIL -> {
                fragment = NotifyDetailFragment()
            }
            PageIndex.COUPON -> {
                val type = mBundle?.getInt(CouponFragment.BUNDLE_TYPE)
                type?.let {
                    fragment = CouponFragment.newInstance(it)
                }
            }
            PageIndex.CART_ORDER_INFO -> {
                val ids = mBundle?.getStringArray(OrderConfirmListFragment.CART_IDS)
                ids?.let {
                    fragment = OrderConfirmListFragment.newInstance(it)
                }
            }
            PageIndex.ACCOUNT_BINDING -> {
                fragment = AccountFragment()
            }
            PageIndex.BIND_PHONE -> {
                val isBind= mBundle?.getBoolean(BindPhoneFragment.TYPE_BIND)?:true
                fragment = BindPhoneFragment.newInstance(isBind)
            }
        }
        if (fragment != null){
            if (fragment!!.isAdded){
                transaction.show(fragment!!)
            }else{
                transaction.add(R.id.fragment_container_fl,fragment!!,fragment!!::class.java.simpleName)
                transaction.addToBackStack(null)
            }
            transaction.commitAllowingStateLoss()
        }
    }

    private fun hideAllFragments(transaction: FragmentTransaction){
        mFragmentList.forEach {
            transaction.hide(it)
        }
    }

    /**
     * 关闭Fragment
     */
    fun close(){
        if (supportFragmentManager.backStackEntryCount <= 1){
            finish()
        }else{
            supportFragmentManager.popBackStack()
        }
    }

    override fun onBack() {
        close()
    }

    override fun onBackPressed() {
        close()
    }
}